package com.training.api.service;

import com.training.bean.Collect;
import com.training.bean.Course;
import com.training.api.repository.CollectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CollectService {
    
    @Autowired
    private CollectRepository collectRepository;
    /**
     * 添加收藏
     * @param uid 用户ID
     * @param cid 课程内容ID
     * @return 收藏对象
     */
    public Collect addCollect(int uid, int cid) {
        // 检查是否已经收藏
        if (isCollected(uid, cid)) {
            throw new RuntimeException("该内容已被收藏");
        }
        
        Collect collect = new Collect();
        collect.setUid(uid);
        collect.setCid(cid);
        collect.setCreate_date(new Date());
        collect.setUpdata_date(new Date());
        
        return collectRepository.save(collect);
    }
    
    /**
     * 取消收藏
     * @param uid 用户ID
     * @param cid 课程内容ID
     */
    public void removeCollect(int uid, int cid) {
        // 查找对应的收藏记录
        List<Collect> collects = collectRepository.findByUserId(uid);
        for (Collect collect : collects) {
            if (collect.getCid() == cid) {
                collectRepository.delete(collect);
                break;
            }
        }
    }
    
    /**
     * 获取用户收藏的课程列表(使用多表联查优化性能)
     * @param uid 用户ID
     * @return 课程列表
     */
    public List<Course> getUserCollectCourses(int uid) {
        // 使用JPQL三表联查直接获取用户收藏的课程及学习进度，避免N+1查询问题
        return collectRepository.findUserCollectCoursesWithProgress(uid);
    }
    
    /**
     * 检查是否已收藏
     * @param uid 用户ID
     * @param cid 课程内容ID
     * @return 是否已收藏
     */
    public boolean isCollected(int uid, int cid) {
        return collectRepository.existsByUserIdAndContentId(uid, cid) > 0;
    }

}